package staff

import (
	"duoke/model"
	"duoke/service"
	"duoke/tables"
	"duoke/utils/gconv"
	"duoke/utils/gtime"
	"duoke/utils/orm"
	"duoke/utils/response"
	"fmt"
	"github.com/gin-gonic/gin"
)

var Group = new(groupCtl)

type groupCtl struct{}

func (ctl *groupCtl) List(c *gin.Context) {
	staffR, _ := service.Request.Staff(c)
	accountR, _ := service.Request.Account(c)
	var req model.ReqList
	if err := c.ShouldBind(&req); err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	where := "goods_id = '" + gconv.String(staffR.GoodsId) + "' AND staff_id=" + gconv.String(staffR.Id) + " "
	if req.Keyword != "" {
		where += "AND (user_id ='" + req.Keyword + "' OR order_no ='" + req.Keyword + "' OR nickname ='" + req.Keyword + "' OR name ='" + req.Keyword + "' OR phone ='" + req.Keyword + "' )"
	}
	if req.Keyword2 != "" {
		where2 := "is_head =0 AND pay_state = 1 AND (user_id ='" + req.Keyword2 + "' OR order_no ='" + req.Keyword2 + "' OR nickname ='" + req.Keyword2 + "' OR name ='" + req.Keyword2 + "' OR phone ='" + req.Keyword2 + "' )"
		order2 := new(tables.Order)
		has, _ := orm.Db.Desc("id").Where("acid =?", accountR.Id).Where(where2).Get(order2)
		if has {
			where += "AND id = " + gconv.String(order2.GroupId) + " "
		} else {
			where += "AND id = -1 "
		}
	}
	if req.State != "" {
		where += "AND hx_state = '" + req.State + "' "
	}
	if req.GroupState != "" {
		where += "AND group_state = '" + req.GroupState + "' "
	}
	if req.IsRobot != "" {
		where += "AND is_robot = '" + req.IsRobot + "' "
	}
	if req.TimeRange != nil && len(req.TimeRange) == 2 {
		startTime := gtime.StrToTime(req.TimeRange[0])
		endTime := gtime.StrToTime(req.TimeRange[1])
		where += "AND pay_time >= '" + gconv.String(startTime) + "' "
		where += "AND pay_time <= '" + gconv.String(endTime) + "' "
		fmt.Println(where)
	}
	if req.GroupNum != "" {
		where += "AND group_num = '" + req.GroupNum + "' "
	}
	if req.GroupMemberNum != "" {
		where += "AND group_member_num = '" + req.GroupMemberNum + "' "
	}
	if req.IsNewOld != "" {
		where += "AND is_new_old = '" + req.IsNewOld + "' "
	}
	list, err := service.Group.List(c, where, 10000, "")
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "", list)
}
